<template>
  <div class="catalog-wrapper">
    <ws-catalog-path
      :path="path"
      @goback="handleGoBack">
    </ws-catalog-path>
    <ws-catalog-gallery
      :data="data"
      @click="handleItemClick"
      @delete="handleItemDelete">
    </ws-catalog-gallery>
  </div>
</template>

<script>

import WsCatalogPath from './CatalogPath'
import WsCatalogGallery from './CatalogGallery'
import * as catalogService from '@/api/services/catalogService'
import * as imageService from '@/api/services/imageService'

export default {
  name: 'WsCatalogApp',
  components: {
    WsCatalogPath,
    WsCatalogGallery
  },
  props: {
  },
  data () {
    return {
      path: [],
      data: []
    }
  },
  computed: {
  },
  created () {
    this.path = [{
      id: 'ROOT',
      name: '首页'
    }]
    this.doRefresh()
  },
  methods: {
    /**
     * 处理返回操作
     */
    handleGoBack (item) {
      for (let i = this.path.length - 1; i >= 0; i--) {
        const ph = this.path[i]
        if (ph.id === item.id) {
          break
        }
        this.path.splice(i, 1)
      }
      this.doRefresh()
    },

    /**
     * 删除
     */
    handleItemDelete (item) {
    },

    /**
     * 点击
     */
    handleItemClick (item) {
      if (item.resType === 'FOLDER') {
        this.path.push(item)
        this.doRefresh()
      }
    },

    /**
     * 刷新数据
     */
    doRefresh () {
      let curId = ''
      if (this.path.length > 1) {
        let lastItem = this.path[this.path.length - 1]
        curId = lastItem.id
      }
      catalogService.list(curId, {}).then(response => {
        this.data = this.parseData(response.data)
      }).catch(error => {
        console.log('error: ', error)
      })
    },

    /**
     * 解析数据
     * @param {Array} data 数据
     */
    parseData (data) {
      data = data || []
      data.forEach(d => {
        if (d.resType === 'IMAGE') {
          d.url = imageService.getUrl(d.resId)
        }
      })
      return data
    }
  }
}
</script>
